package fun.huixi.weiju.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import fun.huixi.weiju.constant.Constant;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 公共字段，自动填充值
 * @author Administrator
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {

    private final static String CREATE_TIME = "createTime";
    private final static String UPDATE_TIME = "updateTime";
    private final static String DEL_FLAG = "delFlag";
    private final static String STATUS_FLAG = "statusFlag";
    private final static String VERSION = "version";

    @Override
    public void insertFill(MetaObject metaObject) {

        LocalDateTime localDateTime = LocalDateTime.now();

        //创建时间
        setFieldValByName(CREATE_TIME, localDateTime, metaObject);

        //更新时间
        setFieldValByName(UPDATE_TIME, localDateTime, metaObject);

        // 状态标识符
        Object fieldValByName = getFieldValByName(STATUS_FLAG, metaObject);
        if(fieldValByName==null){
            setFieldValByName(STATUS_FLAG, Constant.STATUS_FLAG, metaObject);
        }


        //删除标识
        setFieldValByName(DEL_FLAG, Constant.B_FALSE, metaObject);

        //乐观锁
        setFieldValByName(VERSION, Constant.VERSION, metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        LocalDateTime localDateTime = LocalDateTime.now();

        //更新时间
        setFieldValByName(UPDATE_TIME, localDateTime, metaObject);
    }
}